package com.ccg.plat.presentation.ui.feature9.viewmodel

import android.app.Application
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.MutableLiveData
import com.ccg.plat.data.local.cache.UserInfoCache
import com.ccg.plat.presentation.common.base.viewmodel.BaseViewModelC
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.consumeAsFlow
import timber.log.Timber

/**
 * @author : C4_雍和
 * 描述 :
 * 主要功能 :
 * 维护人员 : C4_雍和
 * date : 2025/9/19 10:13
 */
class AdminViewModel(application: Application) : BaseViewModelC(application) {
    //定义意图
    sealed class ContentIntent {
        /**
         * 获取代理商信息
         */
        object GetAgentInfo : ContentIntent()
    }

    data class NaviViewState(var errMsg: MutableLiveData<String> = MutableLiveData(), var registrationId: String = "")

    val newsChannel = Channel<ContentIntent>(Channel.UNLIMITED)
    var uiState by mutableStateOf(NaviViewState())

    init {
        handleIntent()
    }

    private fun handleIntent() {
        launch(Dispatchers.IO) {
            newsChannel.consumeAsFlow().collect { data ->
                when (data) {
                    is ContentIntent.GetAgentInfo -> {
                        initData()
                    }
                }
            }
        }
    }

    suspend fun initData() {
        //如果没有缓存请求服务器获取最新版本
        val json = retrofit.getNetData("${UserInfoCache.getBaseUrl()}/agentinfo.json").string()
        Timber.e("${UserInfoCache.getBaseUrl()}/agentinfo.json")
        Timber.e(json)
        val listData = GsonBuilder().create().fromJson<List<String>>(json, object : TypeToken<List<String>>() {}.type)
        UserInfoCache.setUserVip(listData.contains(UserInfoCache.getJpushId()))
    }
}